<template>
  <div style="border: 1px solid #ccc">
    <!-- <input type="file" @change="handleFileUpload" accept=".docx" /> -->
    <div style="display: flex; align-items: center; border-bottom: 1px solid #ccc">
      <Toolbar style="border-bottom: 0; flex-shrink: 0" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
      <button style="margin-left: 10px; padding: 4px 8px" @click="exportToWord">导出为Word</button>
    </div>
    <Editor style="overflow-y: hidden;" :modelValue="modelValue" :defaultConfig="editorConfig"
      :mode="mode" @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed"
      @onFocus="handleFocus" @onBlur="handleBlur" @customAlert="customAlert" @customPaste="customPaste" />
  </div>
</template>
<script setup>
  import '@wangeditor/editor/dist/css/style.css' // 引入 css

  import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { saveAs } from "file-saver";
  // import docx2html from 'docx2html';


  const props = defineProps({
    modelValue: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入内容...'
    }
  });

  const emits = defineEmits(['update:modelValue']);
  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef()


  // 模拟 ajax 异步获取内容
  onMounted(() => {

  })

  const toolbarConfig = {}
  const editorConfig = { placeholder: props.placeholder, htmlTags: true,  pasteFilterStyle: false,
    pasteIgnoreImg: false,
    customRenderElem: (domNode, node, editor) => {
      console.log(domNode);
      return domNode; // 直接返回原始DOM节点
    },
    
    // 不自动转换特殊字符
    encodeHtml: false,}

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })

  const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
  }
  const handleChange = (editor) => {
    const html = editor.getHtml() // 获取编辑器内容的HTML
    emits('update:modelValue', html) // 触发更新父组件的modelValue
  }
  const handleDestroyed = (editor) => {
  }
  const handleFocus = (editor) => {
  }
  const handleBlur = (editor) => {
  }
  const customAlert = (info, type) => {
    alert(`【自定义提示】${type} - ${info}`)
  }
  const customPaste = (editor, event, callback) => {
    // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
    // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
    // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

    // 自定义插入内容
    editor.insertText('xxx')

    // 返回 false ，阻止默认粘贴行为
    event.preventDefault()
    callback(false) // 返回值（注意，vue 事件的返回值，不能用 return）

    // 返回 true ，继续默认的粘贴行为
    // callback(true)
  }

  // setDom
  const setDom = (content) => {
    console.log('setDom', editorRef.value)
    editorRef.value.dangerouslyInsertHtml(content) 
  }
  defineExpose({setDom})
  const fixBase64MimeTypes = (html) => {
    // 匹配data:image/*;base64, 或不规范的MIME类型
    return html.replace(/src="data:image\/(\*|[a-z]+);base64,/g, (match, type) => {
      // 如果是通用类型(*)或不规范类型，根据内容智能判断
      if (type === '*' || !['png', 'jpeg', 'jpg', 'gif', 'webp'].includes(type)) {
        // 这里可以添加更复杂的类型检测逻辑
        // 简化版：默认使用png（最通用的无损格式）
        return 'src="data:image/png;base64,';
      }
      
      // 保留正确的MIME类型
      return match;
    });
  };
  const exportToWord = async () => {
    const editor = editorRef.value;
    if (!editor) {
      customAlert('编辑器未初始化，无法导出', 'warning');
      return;
    }

    const html = editor.getHtml();
    if (!html) {
      customAlert('编辑器内容为空，无法导出', 'warning');
      return;
    }
    // 预处理表格样式（关键）
    let processedHtml = processTableStyles(html);
    processedHtml = processImages(processedHtml);
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = processedHtml;
    tempDiv.id = 'editor-content';


    
      // 构建包含 HTML 内容的完整 HTML 文档字符串
    const fullHtmlContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body>
          ${tempDiv.outerHTML}
        </body>
      </html>
    `;
    const blob = htmlDocx.asBlob(fullHtmlContent);
    saveAs(blob, 'editor-content.docx');


    
  }
  // 预处理表格样式
  function processTableStyles(html) {
    // 1. 将表格类转换为内联样式
    html = html.replace(/<table([^>]*)class="([^"]*)"([^>]*)>/gi, (match, before, classes, after) => {
      let inlineStyles = '';
      
      // 处理常用表格类
      if (classes.includes('table-bordered')) {
        inlineStyles += 'border-collapse:collapse;';
      }
      if (classes.includes('table-hover')) {
        inlineStyles += 'background-color:#f5f5f5;';
      }
      
      // 添加到style属性
      if (inlineStyles) {
        if (before.includes('style="')) {
          before = before.replace(/style="([^"]*)"/, `style="$1 ${inlineStyles}"`);
        } else {
          before += ` style="${inlineStyles}"`;
        }
      }
      return `<table${before}${after}>`;
    });
    
    // 2. 确保单元格有边框
    html = html.replace(/<td([^>]*)>/gi, '<td$1 style="border:1px solid #ddd;padding:8px;">');
    html = html.replace(/<th([^>]*)>/gi, '<th$1 style="background-color:#f5f2f0;border:1px solid #ddd;padding:8px;font-weight:bold;border-right-width: 3px;line-height: 1.5;">');
    html = html.replace(/<table([^>]*(?!width)[^>]*?)>/gi, '<table$1 cellspacing="0" cellpadding="0" width="100%" style="border-collapse:collapse;width:100%;table-layout:fixed;">')
      // 情况2：有宽度属性但非100%，替换为100%
      .replace(/<table([^>]*?)width="([^"]+)"([^>]*?)>/gi, '<table$1 cellspacing="0" cellpadding="0" width="100%" style="width:100%;table-layout:fixed;"$3>')
      // 情况3：有style但无宽度，添加宽度
      .replace(/<table([^>]*?)style="([^"]*?)"([^>]*?)>/gi, (match, before, style, after) => {
        if (!style.includes('width')) {
          return `<table${before} cellspacing="0" cellpadding="0" style="${style}width:100%;table-layout:fixed;"${after}>`;
        }
        return match;
      });

    const doc = new DOMParser().parseFromString(html, 'text/html');
    // 自定义隔行换色类
    // const oddClass = 'table-odd';
    // const evenClass = 'table-even';
    const oddBgColor = '#f9f9f9';
    const evenBgColor = '#ffffff';
    // 处理所有包含这些类的表格
    const tables = doc.querySelectorAll(`table`);
    tables.forEach(table => {
      const rows = table.querySelectorAll('tr');
      rows.forEach((row, index) => {
        const isEvenRow = index % 2 === 0;
        const bgColor = isEvenRow ? evenBgColor : oddBgColor;
        
        // 为行内每个单元格设置背景色
        const cells = row.querySelectorAll('td, th');
        cells.forEach(cell => {
          const style = cell.getAttribute('style') || '';
          if (!style.includes('background-color')) {
            cell.setAttribute('style', `${style} background-color: ${bgColor};`);
          }
        });
      });
      
      // 移除表格的自定义类
      // table.classList.remove(oddClass, evenClass);
    });
    return doc.body.innerHTML;
  }

  function processImages(html) {
    const doc = new DOMParser().parseFromString(html, 'text/html');
    
    // 处理所有图片
    const images = doc.querySelectorAll('img');
    images.forEach(img => {
      console.log(img)
      // 确保图片有明确的宽高属性
      // 如果style中宽度存在，则使用style中的宽度
      if (img.style.width) {
        img.setAttribute('width', img.style.width.replace('px', ''));
      }
      // 如果style中高度存在，则使用style中的高度
      if (img.style.height) {
        img.setAttribute('height', img.style.height.replace('px', ''));
      }
      
      // 可选：将图片转换为Base64（确保Word能正确加载）
      if (img.src.startsWith('http') && !img.src.startsWith('data:')) {
        convertImageToBase64(img);
      }
    });
    
    return doc.body.innerHTML;
  }
  // 图片转Base64（可选，需要异步处理）
  async function convertImageToBase64(img) {
    try {
      const response = await fetch(img.src);
      const blob = await response.blob();
      
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          img.src = reader.result; // 设置为Base64格式
          resolve();
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    } catch (error) {
      console.error('图片转换失败:', error);
      // 转换失败时保持原URL
    }
  }
//   const handleFileUpload = async (e) => {
//   const file = e.target.files[0];
//   if (!file) return;

//   const reader = new FileReader();
//   reader.onload = async (event) => {
//     const arrayBuffer = event.target.result;
//     const result = await docx2html( arrayBuffer );
//     console.log("Result:", result.content.outerHTML);
//     console.log(editorRef.value)
//     editorRef.value.dangerouslyInsertHtml(result.content.outerHTML)
//     // parseDocument(tempDiv.innerHTML);
//     // editorContent.value = `<div id="A" style="background-color: transparent; min-height: 1000px; width: 100%; padding-top: 20px; overflow: auto;"><section style="width: 793px; min-height: 1122px; padding: 96px; column-gap: 48px;"><h1 class=" a _1" id="YW7Bh" style="margin-bottom: 3px; margin-top: 6px; line-height: 150%;"><span class=" a0">一、</span><span class=" a0" style="color: rgb(196, 188, 150);">ESG是什么</span></h1></section></div>`;
//   };
//   reader.readAsArrayBuffer(file);
// };
  
</script>